<template>
  <view class="page-wrap page-top-background">
    <!-- Header -->
    <c-nav-bar title="个人中心" placeholder left-icon="" />
    <view class="p-1">
      <!-- Profile Info -->
      <view class="mb-8 mt-4 flex flex-col items-center">
        <view class="mb-3 h-20 w-20 flex items-center justify-center rounded-full bg-gray-200">
          <u-icon name="account" size="40" color="#999999" />
        </view>
        <text class="text-lg text-white font-medium">
          {{ userName }}
        </text>
      </view>

      <!-- Menu List -->
      <view class="mx-4 overflow-hidden rounded-lg bg-white shadow-sm">
        <view
          v-for="(item, index) in showMenus"
          :key="index"
          class="flex items-center px-4 py-4 active:bg-gray-50"
          :class="{ 'border-b border-gray-100': index !== menuItems.length - 1 }"
          @click="handleMenuClick(item)"
        >
          <u-icon
            :name="item.icon"
            size="20"
            color="#3b82f6"
            class="mr-3"
          />
          <text class="flex-1 text-gray-700">
            {{ item.title }}
          </text>
          <u-icon name="arrow-right" size="16" color="#999999" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { UserTypeE } from '@/store/modules/user/enum';
import { usePermission } from '@/hooks';
import { useUserStore } from '@/store';
import { setToken } from '@/utils';
import { ref } from 'vue';
import { menuItems } from './const';

const userType = ref<UserTypeE | undefined>();
const userName = ref<string | undefined>();
const showMenus = ref<typeof menuItems>([]);

const userStore = useUserStore();

watchEffect(() => {
  userType.value = userStore.user_type;
  userName.value = userStore.user_name;
});

watchEffect(() => {
  showMenus.value = menuItems;
});

const handleLogout = () => {
  setToken('');
  uni.$u.route({
    type: 'reLaunch',
    url: '/pages/common/login/index',
  });
};

const handleMenuClick = (item: typeof menuItems[0]) => {
  if (item.path) {
    uni.navigateTo({
      url: item.path,
    });
  }
  else {
    switch (item.key) {
      case 'logout':
        handleLogout();
        break;

      default:
        break;
    }
  }
};
// 登录鉴权，微信小程序端点击tabbar的底层逻辑不触发uni.switchTab，需要在页面onShow生命周期中校验权限
onShow(async () => {
  const hasPermission = await usePermission();
  console.log(hasPermission ? '已登录' : '未登录，拦截跳转');
});
</script>

<style lang="scss" scoped>
//
page{
  background-color: #fff;
}
</style>
